<template>
  <div class="fornt_center">
    <el-card style="width:20%">
      <el-row>
        <el-col :span="24"
                align="middle">

          <el-form :model="form"
                   :rules="rules"
                   ref="form">
            <el-form-item label="用户名"
                          prop="username">
              <el-input v-model="form.username"></el-input>
            </el-form-item>
            <el-form-item label="密码"
                          prop="password">
              <el-input v-model="form.password"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary"
                         @click="submitForm('form')">登录</el-button>
              <el-button @click="resetForm('form')">重置</el-button>
            </el-form-item>
            <el-link @click="pushIndex"
                     type="primary">随便看看</el-link>
          </el-form>
        </el-col>
      </el-row>
    </el-card>
  </div>

</template>
<script>
export default {
  name: 'Login',
  components: {},
  props: {},
  data() {
    return {
      form: {
        username: '',
        password: '',
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 20,
            message: '长度在 3 到 20 个字符',
            trigger: 'blur',
          },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 3,
            max: 20,
            message: '长度在 3 到 20 个字符',
            trigger: 'blur',
          },
        ],
      },
    }
  },
  created() {},
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios.post('/user/login', this.form).then((res) => {
            // 获取jwt和用户信息
            let jwt = res.headers['authorization']
            let userInfo = res.data.data
            // 保存到浏览器
            this.$store.commit('SET_JWT', jwt)
            this.$store.commit('SET_USERINFO', userInfo)
            this.$router.push('/blogs/list')
          })
        } else {
          return false
        }
      })
    },
    pushIndex() {
      this.$router.push('/')
    },
  },
  watch: {},
  computed: {},
  mounted() {},
}
</script>
<style scoped>
</style>